package com.zhugang.week08;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program algorithms
 * @description: subsetsWithDup
 * @author: chanzhugang
 * @create: 2022/08/04 22:21
 */
public class SubsetsWithDup {

    /**
     * 90 子集 II
     *
     * @param nums
     * @return
     */
    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        // nums中包含重复元素
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int count = 1;
            if (map.containsKey(nums[i])) {
                count += map.get(nums[i]);
            }
            map.put(nums[i], count);
        }

        int n = map.size();
        int[] uniqueNums = new int[n];
        int[] counts = new int[n];
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                uniqueNums[k] = nums[i];
                counts[k] = map.get(nums[i]);
                k++;
                map.remove(nums[i]);
            }
        }
        // 以上操作：元素出现的个数，放到两个数组里一一对应
        backtrack(uniqueNums, counts, 0, new ArrayList<Integer>());
        return result;
    }

    private void backtrack(int[] uniqueNums, int[] counts, int k, List<Integer> path) {
        if (k == uniqueNums.length) {
            // 结束条件，可行解
            result.add(new ArrayList<>(path));
            return;
        }

        for (int count = 0; count <= counts[k]; count++) {
            // 转成0-1背包问题，放几个
            for (int i = 0; i < count; i++) {
                path.add(uniqueNums[k]);
            }

            backtrack(uniqueNums, counts, k + 1, path);
            for (int i = 0; i < count; i++) {
                path.remove(path.size() - 1);
            }
        }

    }
}